// =================== 纯数据和工具函数可放在全局作用域 ===================

// 验证码相关函数
function generateCaptcha() {
    const canvas = document.getElementById('captchaCanvas');
    const ctx = canvas.getContext('2d');
    const captchaText = generateRandomText();
    
    // 保存验证码到全局变量
    window.currentCaptcha = captchaText;
    
    // 清空画布
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制文字
    ctx.font = '28px Arial';
    ctx.fillStyle = '#333';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // 添加干扰线
    for (let i = 0; i < 3; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
        ctx.stroke();
    }
    
    // 添加干扰点
    for (let i = 0; i < 50; i++) {
        ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
        ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 2, 2);
    }
    
    // 绘制验证码文字
    for (let i = 0; i < captchaText.length; i++) {
        const x = 20 + i * 25;
        const y = canvas.height / 2;
        const rotate = (Math.random() - 0.5) * 0.3;
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate(rotate);
        ctx.fillText(captchaText[i], 0, 0);
        ctx.restore();
    }
}

function generateRandomText() {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let result = '';
    for (let i = 0; i < 4; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

// 模拟菜单数据
const mockMenus = {
    admin: [
        {
            title: '用户管理',
            icon: 'fa-users',
            desc: '管理系统用户账号和权限'
        },
        {
            title: '系统设置',
            icon: 'fa-cog',
            desc: '配置系统参数和基础数据'
        }
    ],
    manager: [
        {
            title: '物资管理',
            icon: 'fa-boxes',
            desc: '管理急救车物资库存和分类'
        },
        {
            title: '出入库记录',
            icon: 'fa-history',
            desc: '查看物资出入库历史记录'
        }
    ],
    doctor: [
        {
            title: '急救物资申请',
            icon: 'fa-ambulance',
            desc: '申请急救车物资使用'
        },
        {
            title: '物资查询',
            icon: 'fa-search',
            desc: '查询物资库存和使用情况'
        },
        {
            title: '急救申请审批',
            icon: 'fa-check-circle',
            desc: '审批急救物资使用申请'
        },
        {
            title: '科室物资管理',
            icon: 'fa-clipboard-list',
            desc: '管理科室物资使用情况'
        }
    ]
};

// =================== 所有DOM相关操作全部放在DOMContentLoaded事件内 ===================

document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const step1 = document.getElementById('step1');
    const loginForm = document.getElementById('loginForm');
    const backToRole = document.getElementById('backToRole');
    const roleButtons = document.querySelectorAll('.role-btn');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const usernameError = document.getElementById('usernameError');
    const passwordError = document.getElementById('passwordError');
    const loginResult = document.getElementById('loginResult');
    const loginBtn = document.getElementById('loginBtn');
    const rememberMe = document.getElementById('rememberMe');
    const togglePassword = document.getElementById('togglePassword');
    const forgotPassword = document.getElementById('forgotPassword');
    const signUp = document.getElementById('signUp');
    const captchaInput = document.getElementById('captcha');
    const captchaCanvas = document.getElementById('captchaCanvas');
    const captchaError = document.getElementById('captchaError');
    let selectedRole = '';

    // 初始化验证码
    generateCaptcha();
    
    // 点击验证码图片刷新
    captchaCanvas.addEventListener('click', () => {
        generateCaptcha();
    });

    // step1 身份选择按钮逻辑
    roleButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            selectedRole = btn.getAttribute('data-role');
            step1.style.display = 'none';
            loginForm.style.display = '';
            usernameInput.focus();
        });
    });

    // 回退按钮逻辑
    if (backToRole) {
        backToRole.addEventListener('click', function() {
            loginForm.style.display = 'none';
            step1.style.display = '';
            selectedRole = '';
            usernameInput.value = '';
            passwordInput.value = '';
            captchaInput.value = '';
            loginResult.innerHTML = '';
            clearErrors();
            checkInput();
        });
    }

    // 密码显示/隐藏功能
    if (togglePassword && passwordInput) {
        togglePassword.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const type = passwordInput.type === 'password' ? 'text' : 'password';
            passwordInput.type = type;
            const icon = this.querySelector('i');
            if (icon) {
                icon.className = type === 'password' ? 'fa-solid fa-eye' : 'fa-solid fa-eye-slash';
            }
        });
    }

    // 输入框监听，控制按钮可用
    function checkInput() {
        if (usernameInput.value.trim() && 
            passwordInput.value.trim() && 
            captchaInput.value.trim()) {
            loginBtn.disabled = false;
            loginBtn.style.opacity = 1;
            loginBtn.style.cursor = 'pointer';
            loginBtn.style.background = '#4a90e2';
        } else {
            loginBtn.disabled = true;
            loginBtn.style.opacity = 0.7;
            loginBtn.style.cursor = 'not-allowed';
            loginBtn.style.background = '#b5c6e0';
        }
    }
    usernameInput.addEventListener('input', checkInput);
    passwordInput.addEventListener('input', checkInput);
    captchaInput.addEventListener('input', checkInput);

    // 清除错误信息
    function clearErrors() {
        usernameError.textContent = '';
        usernameError.style.display = 'none';
        usernameError.classList.remove('shake');
        passwordError.textContent = '';
        passwordError.style.display = 'none';
        passwordError.classList.remove('shake');
        captchaError.textContent = '';
        captchaError.style.display = 'none';
        captchaError.classList.remove('shake');
        loginResult.textContent = '';
        loginResult.className = 'login-result';
        loginResult.style.display = 'none';
        loginResult.classList.remove('shake');
    }

    // 显示错误信息
    function showError(message, type = 'login') {
        clearErrors();
        if (type === 'username') {
            usernameError.textContent = message;
            usernameError.style.display = 'block';
            setTimeout(() => {
                usernameError.classList.remove('shake');
                void usernameError.offsetWidth;
                usernameError.classList.add('shake');
            }, 10);
        } else if (type === 'password') {
            passwordError.textContent = message;
            passwordError.style.display = 'block';
            setTimeout(() => {
                passwordError.classList.remove('shake');
                void passwordError.offsetWidth;
                passwordError.classList.add('shake');
            }, 10);
        } else if (type === 'captcha') {
            captchaError.textContent = message;
            captchaError.style.display = 'block';
            setTimeout(() => {
                captchaError.classList.remove('shake');
                void captchaError.offsetWidth;
                captchaError.classList.add('shake');
            }, 10);
        } else {
            loginResult.textContent = message;
            loginResult.className = 'login-result error';
            loginResult.style.display = 'flex';
            setTimeout(() => {
                loginResult.classList.remove('shake');
                void loginResult.offsetWidth;
                loginResult.classList.add('shake');
            }, 10);
        }
    }

    // 显示登录成功
    function showSuccess(msg) {
        clearErrors();
        loginResult.innerHTML = '<i class="fa-solid fa-circle-check"></i>' + msg;
        loginResult.className = 'login-result success';
        loginResult.style.display = 'flex';
    }

    // 自动填充账号和密码（如果有）
    const savedUsername = localStorage.getItem('login_username');
    const savedPassword = localStorage.getItem('login_password');
    const savedRole = localStorage.getItem('login_role');
    if (savedUsername && savedPassword && savedRole) {
        usernameInput.value = savedUsername;
        passwordInput.value = savedPassword;
        rememberMe.checked = true;
        // 自动选择保存的角色
        const savedRoleBtn = document.querySelector(`.role-btn[data-role="${savedRole}"]`);
        if (savedRoleBtn) {
            selectedRole = savedRole;
            savedRoleBtn.classList.add('selected');
            step1.style.display = 'none';
            loginForm.style.display = '';
        }
    }
    checkInput();

    // 登录处理函数
    function handleLogin(e) {
        e.preventDefault();
        loginBtn.classList.add('loading');
        loginBtn.innerHTML = '<span class="loading-spinner"></span>登录中...';
        
        // 验证码检查
        if (captchaInput.value.trim().toLowerCase() !== window.currentCaptcha.toLowerCase()) {
            showError('验证码错误', 'captcha');
            generateCaptcha();
            captchaInput.value = '';
            loginBtn.classList.remove('loading');
            loginBtn.innerHTML = '登录';
            return;
        }
        
        setTimeout(() => {
            const usernameOrEmail = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            const user = (window.mockUsers || mockUsers).find(u =>
                (u.username === usernameOrEmail || u.email === usernameOrEmail)
            );
            
            if (!user) {
                showError('账号不存在', 'username');
            } else if (user.role !== selectedRole) {
                showError('身份选择错误', 'username');
            } else if (user.password !== password) {
                showError('密码错误', 'password');
            } else {
                setTimeout(() => {
                    showSuccess('登录成功，正在跳转...');
                    
                    // 保存登录信息
                    if (rememberMe.checked) {
                        localStorage.setItem('login_username', usernameOrEmail);
                        localStorage.setItem('login_password', password);
                        localStorage.setItem('login_role', selectedRole);
                    } else {
                        localStorage.removeItem('login_username');
                        localStorage.removeItem('login_password');
                        localStorage.removeItem('login_role');
                    }
                    
                    // 保存用户信息到 localStorage
                    const userInfo = {
                        username: user.username,
                        name: user.name,
                        role: user.role,
                        department: user.department,
                        email: user.email,
                        sessionId: generateSessionId(),
                        loginTime: new Date().getTime(),
                        expiresIn: 3600000
                    };
                    localStorage.setItem('currentUser', JSON.stringify(userInfo));
                    
                    // 跳转到主页
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 1000);
                }, 800);
            }
            loginBtn.classList.remove('loading');
            loginBtn.innerHTML = '登录';
        }, 800);
    }

    // 忘记密码点击事件
    function handleForgotPassword(e) {
        e.preventDefault();
        alert('请联系管理员重置密码');
    }

    // 注册点击事件
    function handleSignUp(e) {
        e.preventDefault();
        alert('请联系管理员开通账号');
    }

    if (loginForm) loginForm.addEventListener('submit', handleLogin);
    if (forgotPassword) forgotPassword.addEventListener('click', handleForgotPassword);
    if (signUp) signUp.addEventListener('click', handleSignUp);
}); 

// 生成会话ID的函数
function generateSessionId() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
} 